// component/svg.js
const fs = wx.getFileSystemManager()

import { Base64 } from '@/utils/base64'
const base64 = new Base64()

Component({
    properties: {
        src: {
            type: String,
            value: ''
        },
        color: {
            type: String,
            value: ''
        },
        size: {
            type: String,
            value: '20px'
        }
    },

    observers: {
        'src,color': function (src, color) {
            this.getSvgFile(src, color)
        }
    },
    data: {
        svgData: ''
    },
    lifetimes: {
        attached: function () {
            this.updateColor()
        }
    },
    pageLifetimes: {
        show: function () {
            this.updateColor()
        }
    },
    methods: {
        getSvgFile(src, color) {
            let that = this
            fs.readFile({
                filePath: src,
                encoding: 'UTF-8',
                position: 0,
                success(res) {
                    let sourceFile = res.data
                    let newFile = that.properties.color
                        ? that.changeColor(sourceFile, color)
                        : sourceFile
                    let svgBase64File = base64.encode(newFile)
                    that.setData({
                        svgData: 'data:image/svg+xml;base64,' + svgBase64File
                    })
                },
                fail(res) {
                    console.error(res)
                }
            })
        },

        changeColor(sourceFile, color) {
            let newSvg
            if (/fill=".*?"/.test(sourceFile)) {
                newSvg = sourceFile.replace(/fill="#([0-9A-Fa-f]{6})"/g, (match, hexColor) => {
                    // 如果颜色不是白色 (#FFFFFF)，则替换
                    if (hexColor.toUpperCase() !== 'FFFFFF') {
                        return `fill="${color}"`
                    }
                    return match // 如果是白色，则保留原样
                }) // SVG有默认色
            } else {
                newSvg = sourceFile.replace(/<svg /g, `<svg fill="${color}" `) // 无默认色
            }
            return newSvg
        },
        updateColor() {
            const color = this.properties.color || wx.getStorageSync('primaryColor')
            this.getSvgFile(this.properties.src, color)
        }
    }
})
